//
//  DAOTruffle.m
//  ContactSQL
//
//  Created by m2sar on 05/03/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "DAOTruffle.h"
#import "Contact.h"
#import "Gateway.h"
#import "Coupon.h"

/*
 * code test a mettre dans app delegate *
 
 DAOTruffle * dao = [[DAOTruffle alloc] init];
 UIDevice * device = [UIDevice currentDevice];
 NSString * uuid = [device uniqueIdentifier];
 NSString * pseudo = @"iso";
 Contact * contact = [[Contact alloc] initContact:uuid:pseudo];
 [dao addContact:contact];
 [dao isFavori:contact];
 [dao removeContact:contact];
 
 */

@implementation DAOTruffle
//static sqlite3 * database;

@synthesize database;


- (void)dealloc {
	sqlite3_close(database);
    [super dealloc];
}


/*
 * ouverture de la base de donnee contenant les contacts favoris et les passerelles de preferences
 */
-(id)init
{
	NSString * databaseName = @"Database.sql" ;
	NSArray * documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
	NSString * documentsDir = [documentPaths objectAtIndex:0];
	NSString * databasePath = [documentsDir stringByAppendingPathComponent : databaseName];
	
	NSLog(@"%@",databasePath);
	if(database == nil)
	{
		if(sqlite3_open([databasePath UTF8String],&database) == SQLITE_NULL)
			NSLog(@"ERROR when opening database");
	}
	sqlite3_initialize();
	
	return self;
	
}

/*
 * initailisation avec un chemin absolue de la base de données
 * juste pour les test
 */

- (id)initWithDatabase : (NSString *) testDatabase
{
	
	NSString * databasePath = testDatabase;//@"./Database.sql";
	
	NSLog(@"%@",databasePath);
	if(database == nil)
	{
		if(sqlite3_open([databasePath UTF8String],&database) == SQLITE_NULL)
			NSLog(@"ERROR when opening database");
	}
	sqlite3_initialize();
	
	return self;
	
}


/*
 * ajout d un contact passé en parametre  dans la table Contact de la base de donnee
 */
- (NSInteger) addContact :(Contact *)contact
{
	/*
	 DaoTruffle * dao = [[DaoTruffle alloc] init];
	 Contact * contact = [[Contact alloc] initContact:uuid:pseudo];
	 [dao addContact:contact];
	 */
	NSLog(@"contact a ajojuter => %@", contact);
	char *sql = "insert into Contact (uuid, pseudo) values (?, ?);";
	sqlite3_stmt *stmt ;
	int status = 0;
		
	if (sqlite3_prepare_v2(database, sql, -1, &stmt, nil) == SQLITE_OK ){
			sqlite3_bind_text(stmt,1,[contact.UUID UTF8String], -1, NULL);
			sqlite3_bind_text(stmt,2,[contact.pseudo UTF8String], -1, NULL);
	}
	else {
		NSLog(@"ERREUR LORS DE L AJOUT ");
		status = 1;
	}
	
	if (SQLITE_DONE != sqlite3_step(stmt))
		NSAssert1(status, @"Error while adding contact. '%s'", sqlite3_errmsg(database));
	
	sqlite3_finalize(stmt);
	NSLog(@"add contact : %@", contact);
	return status ;

}

/*
 * suppression d un contact passé en parametre depuis la table Contact de la base de donnee 
 */
- (int) removeContact :(Contact *)contact
{
	/* -- Exepmle d'appel -- */
	
	/*
	 DaoTruffle * dao = [[DaoTruffle alloc] init];
	 Contact * contact = [[Contact alloc] initContact:uuid:pseudo];
	 [dao removeContact:contact];
	 */
	
	char *sql = "delete from Contact where uuid like ? ; ";
	sqlite3_stmt *stmt ;
	int status = 0;
	
	if (sqlite3_prepare_v2(database, sql, -1, &stmt, nil) == SQLITE_OK ){
		sqlite3_bind_text(stmt,1,[contact.UUID UTF8String], -1, NULL);
		
	}
	else {
		NSLog(@"ERREUR LORS DE La SUPPRESSION ");
		status = 1;
	}
	
	if (SQLITE_DONE != sqlite3_step(stmt))
		NSAssert1(0, @"Error while removing contact. '%s'", sqlite3_errmsg(database));
	
	sqlite3_finalize(stmt);
	NSLog(@"remove contact : %@", contact);
	return status ;
}

/*
 *liste tout les contacts de la table Contact de la base de donnee 
 */
- (NSMutableArray * ) getContacts
{
	NSMutableArray * contacts= [[NSMutableArray alloc] init];
	const char * sql = "select * from Contact";
	sqlite3_stmt * smt = nil;
	if(sqlite3_prepare_v2(database, sql, -1, &smt, NULL) == SQLITE_OK) {
			
		while(sqlite3_step(smt) == SQLITE_ROW) {
			
			char * uid = (char *)sqlite3_column_text(smt, 1);
			char * ps = (char *)sqlite3_column_text(smt, 2);
			
			NSString * uuid = (uid == NULL) ? @"" : [NSString stringWithUTF8String:uid];
			NSString * pseudo = (ps == nil) ? @"" : [NSString stringWithUTF8String:ps];
			Contact	* contact = [[Contact alloc] initContact:uuid:pseudo];
			
			[contacts addObject:contact];
			
			[contact release];
		}
	}
	else
	{
		NSLog(@"ERREUR LORS DE LA RECUPERATION '%s'", sqlite3_errmsg(database));
		NSAssert1(0, @"Error while adding contact. '%s'", sqlite3_errmsg(database));
	}
	
	sqlite3_finalize(smt);
	
	return contacts;
}

/*
 * verifie si le contact passé en parametre est deja un favori ou pas
 */

-(BOOL) isFavori: (Contact *) contact
{
	const char * sql = "select * from Contact where uuid like ?";
	sqlite3_stmt * smt = nil;
	if(sqlite3_prepare_v2(database, sql, -1, &smt, NULL) == SQLITE_OK) {
		sqlite3_bind_text(smt,1,[contact.UUID UTF8String], -1, NULL);
		if(sqlite3_step(smt) == SQLITE_ROW)
		{
			//NSLog(@"is favori true contact : %@", contact);
			return TRUE;
		}
	}
	else
	{
		NSLog(@"ERREUR LORS DE LA RECUPERATION");
	}
	//NSLog(@"is favori FALSE contact : %@", contact);
	return FALSE;
}

/*
 * verifie si le gateway passé en parametre est deja un favori ou pas
 */

-(BOOL) isFavoriGateway: (Gateway *) gateway
{
	const char * sql = "select * from Passerelle where ref = 0 and ip like ?";
	sqlite3_stmt * smt = nil;
	if(sqlite3_prepare_v2(database, sql, -1, &smt, NULL) == SQLITE_OK) {
		sqlite3_bind_text(smt,1,[gateway.ip UTF8String], -1, NULL);
		if(sqlite3_step(smt) == SQLITE_ROW)
		{
			NSLog(@"is favori true gateway : %@", gateway);
			return TRUE;
		}
	}
	else
	{
		NSLog(@"ERREUR LORS DE LA RECUPERATION");
	}
	NSLog(@"is favori FALSE gateway : %@", gateway);
	return FALSE;
}

/*
 * ajout d une passerelle de preference dans la table Passerelle de la base de donnee
 */
- (int) addGateway :(Gateway *)gateway
{
	/* -- Exepmle d'appel -- */
	
	/*
	 DAOTruffle * dao = [[DAOTruffle alloc] init];
	 Gateway * pass = [[Gateway alloc] initGatewayRef:@"124.31.322.12" :@"jussieu": 1];
	 Gateway * pass1 = [[Gateway alloc] initGateway:@"125.31.32.12" :@"jussieu"];
	 [dao addGateway:pass];
	 [dao addGateway:pass1];
	 NSLog(@"ref = %@", [dao getRef]);
	 Gateway * pass2 = [[Gateway alloc] initGatewayRef:@"192.31.342.120" :@"censier":1];
	 [dao addGateway:pass2];
	 */
	
	NSLog(@"adding gateway : %@",[gateway description]);
	
	char *sql = "insert into Passerelle (ip, name, ref) values (?, ?, ?) ; ";
	sqlite3_stmt *stmt ;
	int status = 0;
	
	//Sin c'est une nouvelle passerelle de reference on supprime la derniere passerelle de reference
	if (gateway.ref == 1) 
	{
		Gateway * gtRef = [self getRef];
		
		NSLog(@"gtRef : %@",[gtRef description]);
		
		if (gtRef != nil) {
		
			if (gtRef.ip == gateway.ip && gtRef.name == gateway.name) {
				return status;
			} else {
				NSLog(@"[DAOTruffle] Suppression de la passerelle de reference ip %@", gtRef.ip);
				[self removeGatewayRef];
			}
		}
	}
	
	if (sqlite3_prepare_v2(database, sql, -1, &stmt, nil) == SQLITE_OK ){
		
		sqlite3_bind_text(stmt,1,[gateway.ip UTF8String], -1, NULL);
		sqlite3_bind_text(stmt,2,[gateway.name UTF8String], -1, NULL);
		sqlite3_bind_int(stmt, 3, gateway.ref);
	}
	else {
		NSLog(@"ERREUR LORS DE L AJOUT ");
		status = 1;
	}
	
	if (SQLITE_DONE != sqlite3_step(stmt))
		NSAssert1(0, @"Error while adding passerelle. '%s'", sqlite3_errmsg(database));
	
	sqlite3_finalize(stmt);
	return status ;
	
}

/*
 * suppression d une passerelle passé en parametre depuis la table Passerelle de la base de donnee
 */
- (int) removeGatewayRef
{
	/* -- Exepmle d'appel -- */
	
	/*
	 DaoTruffle * dao = [[DaoTruffle alloc] init];
	 LaPasserelle * pass = [[LaPasserelle alloc] initLaPasserelle:ip :name];
	 [dao removeGateweay:pass];
	 */
	
	char *sql = "delete from Passerelle where ref = 1 ; ";
	sqlite3_stmt *stmt ;
	if (sqlite3_prepare_v2(database, sql, -1, &stmt, nil) != SQLITE_OK ){
		NSAssert1(0, @"Error while deleting passerelle. '%s'", sqlite3_errmsg(database));	
	}
	int status = 0;
	
	if (SQLITE_DONE != sqlite3_step(stmt))
		NSAssert1(0, @"Error while deleting passerelle. '%s'", sqlite3_errmsg(database));
	sqlite3_finalize(stmt);
	return status;
	
}

/*
 * suppression d une passerelle passé en parametre depuis la table Passerelle de la base de donnee
 */
- (int) removeGateway :(Gateway *)gateway
{
	/* -- Exepmle d'appel -- */
	
	/*
	 DaoTruffle * dao = [[DaoTruffle alloc] init];
	 LaPasserelle * pass = [[LaPasserelle alloc] initLaPasserelle:ip :name];
	 [dao removeGateweay:pass];
	 */
	
	char *sql = "delete from Passerelle where ip like ? ; ";
	sqlite3_stmt *stmt ;
	int status = 0;
	
	if (sqlite3_prepare_v2(database, sql, -1, &stmt, nil) == SQLITE_OK ){
		sqlite3_bind_text(stmt, 1, [gateway.ip UTF8String], -1, NULL);
		
	}
	else {
		NSLog(@"ERREUR LORS DE La SUPPRESSION ");
		status = 1;
		
	}
	if (SQLITE_DONE != sqlite3_step(stmt))
		NSAssert1(0, @"Error while deleting passerelle. '%s'", sqlite3_errmsg(database));
	sqlite3_finalize(stmt);
	return status;

}

/*
 *liste toutes les passerelles  depuis  la table Passerelle de la base de donnee 
*/
- (NSMutableArray *) getGateways
{
	NSMutableArray * gateways = [[NSMutableArray alloc] init];
	const char * sql = "select * from Passerelle where ref = 0";
	sqlite3_stmt * smt;
	if(sqlite3_prepare_v2(database, sql, -1, &smt, NULL) == SQLITE_OK) {
		
		while(sqlite3_step(smt) == SQLITE_ROW) {
			char * ip2 = (char *)sqlite3_column_text(smt, 1);
			char * nm = (char *)sqlite3_column_text(smt, 2);
			
			NSString * ip = (ip2 == NULL) ? @"" : [NSString stringWithUTF8String:ip2];
			NSString * name = (nm == nil) ? @"" : [NSString stringWithUTF8String:nm];
			
			Gateway * gate = [[Gateway alloc] initGateway:ip :name];
			
			[gateways addObject:gate];
			
			[gate release];
		}
	}
	
	sqlite3_finalize(smt);
	
	return gateways;
	
}

/*
 * La passerelle de reference dela deeniere connexion
 */
- (Gateway *) getRef
{
	const char * sql = "select * from Passerelle where ref = 1";
	sqlite3_stmt * smt;
	Gateway * gateway = nil;
	if(sqlite3_prepare_v2(database, sql, -1, &smt, NULL) == SQLITE_OK) {
		if(sqlite3_step(smt) == SQLITE_ROW) {
			char * ip2 = (char *)sqlite3_column_text(smt, 1);
			char * nm = (char *)sqlite3_column_text(smt, 2);
			
			NSString * ip = (ip2 == NULL) ? @"" : [NSString stringWithUTF8String:ip2];
			NSString * name = (nm == nil) ? @"" : [NSString stringWithUTF8String:nm];
			gateway = [[Gateway alloc] initGateway:ip :name];
			
		}
	}
	
	//if (SQLITE_DONE != sqlite3_step(smt))
	//NSAssert1(0, @"Error while getting passerelle ref. '%s'", sqlite3_errmsg(database));
	
	sqlite3_finalize(smt);
	return gateway;
	
}


/*
 *sauvegarde de l etat de l utilisateur dans la table Myself de la base de donnee
 */
- (void) saveSelf: (NSMutableDictionary *)dict 
{
	/* -- Exemple de construction pour appeler cette fonction -- */
	
	/*
	DaoTruffle * dao = [[DaoTruffle alloc] init];
	NSMutableDictionary * dict = [NSMutableDictionary dictionary];
	[dict setValue:@"fab" forKey:@"pseudo"];
	NSDecimalNumber * vis = [[NSDecimalNumber alloc] initWithInt:1];
	[dict setValue:vis forKey:@"visibilite"];
	 [dict setValue:@"disponible" forKey:@"status"];
	[dao saveSelf:dict];
	*/
	
	// On commence par vider la table (une seule ligne dans cette table).
	char *sql = "delete from Myself;";
	sqlite3_stmt *stmt;
	
	// FIXME: vérifier les erreurs?
	sqlite3_prepare_v2(database, sql, -1, &stmt, nil);
	
	if (SQLITE_DONE != sqlite3_step(stmt))
		NSAssert1(0, @"Error while saving info. '%s'", sqlite3_errmsg(database));
	sqlite3_finalize(stmt);
	
	// On réinsère la ligne.
	sql = "insert into Myself (pseudo, visibility, status) values (?, ?, ?);";

	NSString * pseudo = [dict objectForKey:@"pseudo"];
	NSDecimalNumber * visibility = (NSDecimalNumber *)[dict objectForKey:@"visibility"];
	NSString * status = [dict objectForKey:@"status"];
	
	if (sqlite3_prepare_v2(database, sql, -1, &stmt, nil) == SQLITE_OK ){
		sqlite3_bind_text(stmt, 1, [pseudo UTF8String], -1, NULL);
		sqlite3_bind_int(stmt, 2, [visibility intValue]);
		sqlite3_bind_text(stmt, 3, [status UTF8String], -1, NULL);
	}
	
	if (SQLITE_DONE != sqlite3_step(stmt))
		NSAssert1(0, @"Error while saving info. '%s'", sqlite3_errmsg(database));
	sqlite3_finalize(stmt);
}

/*
 *liste de tout les informations (etats)  de l utilisateur depuis la base de donnee
 */
- (NSMutableDictionary *) getInfoSelf
{
	/* -- Pour recuperer less infos -- */
	
	/*
	 NSString * status = [dict objectForKey:@"status"];
	 */
	
	NSMutableDictionary * dict = [NSMutableDictionary dictionary];
	
	const char * sql = "select * from Myself";
	sqlite3_stmt * smt;
	if(sqlite3_prepare_v2(database, sql, -1, &smt, NULL) == SQLITE_OK) {
		while(sqlite3_step(smt) == SQLITE_ROW) {
			char * ps = (char *)sqlite3_column_text(smt, 0);
			int vis = (int)sqlite3_column_int(smt, 1);
			char * st = (char *)sqlite3_column_text(smt, 2);
			
			
			NSString * pseudo = (ps == NULL) ? @"" : [NSString stringWithUTF8String:ps];
			NSString * visibility = [NSString stringWithFormat:@"%d", vis];
			NSString * status = (st == NULL) ? @"" : [NSString stringWithUTF8String:st];
			
			[dict setValue:pseudo forKey:@"pseudo"];
			[dict setValue:visibility forKey:@"visibility"];
			[dict setValue:status forKey:@"status"];
		}
	}
	else NSAssert1(0, @"Error while deleting passerelle. '%s'", sqlite3_errmsg(database)); 
	sqlite3_finalize(smt);
	
	
	return dict;
}


# pragma mark -
# pragma mark GestionCoupon

/*
 *ajout d un coupon passe en parametre dans la table Coupon depuis la base de donnee
 */
- (NSInteger) addCoupon :(Coupon *)coupon
{
	/* -- Exepmle d'appel -- */
	
	/*
	DaoTruffle * dao = [[DaoTruffle alloc] init];
	 Coupon * coupon = [[Coupon alloc]initWithId:idCoupon 
						name:name position:position provider:provider 
						couponCode:couponCode descriptions:descriptions];	 
	 [dao addCoupon:coupon];
	 */
	
	char *sql = "insert into Coupon (id_coupon, name, position, provider, coupon_code, descriptions) values (?, ?, ?, ?, ?, ?);";
	sqlite3_stmt *stmt ;
	int status = 0;
	
	if (sqlite3_prepare_v2(database, sql, -1, &stmt, nil) == SQLITE_OK ){
		sqlite3_bind_text(stmt,1,[coupon.idCoupon UTF8String], -1, NULL);
		sqlite3_bind_text(stmt,2,[coupon.name UTF8String], -1, NULL);
		sqlite3_bind_text(stmt,3,[coupon.position UTF8String], -1, NULL);
		sqlite3_bind_text(stmt,4,[coupon.provider UTF8String], -1, NULL);
		sqlite3_bind_text(stmt,5,[coupon.couponCode UTF8String], -1, NULL);
		sqlite3_bind_text(stmt,6,[coupon.descriptions UTF8String], -1, NULL);
	}
	else {
		NSLog(@"ERREUR LORS DE L AJOUT ");
		status = 1;
	}
	
	if (SQLITE_DONE != sqlite3_step(stmt))
		NSAssert1(0, @"Error while adding coupon. '%s'", sqlite3_errmsg(database));
	
	sqlite3_finalize(stmt);
	return status ;
	
}

/*
 *suppression d un coupon passe en parametre depuis la table Coupon de la base de donnee
 */
- (int) removeCoupon :(Coupon *)coupon
{
	/* -- Exemple d'appel -- */
	
	/*
	 DaoTruffle * dao = [[DaoTruffle alloc] init];
	 Coupon * coupon = [[Coupon alloc]initWithId:idCoupon 
						name:name position:position provider:provider 
						couponCode:couponCode descriptions:descriptions];	 
	 [dao removeCoupon:coupon];
	 */
	
	char *sql = "delete from Coupon where id_coupon = ? ; ";
	sqlite3_stmt *stmt;
	int status = 0;
	
	if (sqlite3_prepare_v2(database, sql, -1, &stmt, nil) == SQLITE_OK ){
		sqlite3_bind_text(stmt,1,[coupon.idCoupon UTF8String], -1, NULL);
		
	}
	else {
		NSLog(@"ERREUR LORS DE La SUPPRESSION ");
		status = 1;
	}
	
	if (SQLITE_DONE != sqlite3_step(stmt))
		NSAssert1(0, @"Error while removing coupon. '%s'", sqlite3_errmsg(database));
	
	sqlite3_finalize(stmt);
	return status ;
}

/*
 *liste toutes les Coupons  depuis  la table Coupon de la base de donnee 
 */
- (NSMutableArray * ) getCoupons
{
	NSMutableArray * coupons = [[NSMutableArray alloc] init];
	const char * sql = "select * from Coupon";
	sqlite3_stmt * smt = nil;
	
	if(sqlite3_prepare_v2(database, sql, -1, &smt, NULL) == SQLITE_OK) {
		while(sqlite3_step(smt) == SQLITE_ROW) {
			
			char * nameC = (char *)sqlite3_column_text(smt, 1);
			char * descriptionsC = (char *)sqlite3_column_text(smt, 2);
			char * providerC = (char *)sqlite3_column_text(smt, 3);
			char * couponCodeC = (char *)sqlite3_column_text(smt, 4);
			char * idCouponC = (char *)sqlite3_column_text(smt, 5);
			char * positionC = (char *)sqlite3_column_text(smt, 6);
			
			NSString * name = (nameC == NULL) ? @"" : [NSString stringWithUTF8String:nameC];
			NSString * descriptions = (descriptionsC == NULL) ? @"" : [NSString stringWithUTF8String:descriptionsC];
			NSString * provider = (providerC == NULL) ? @"" : [NSString stringWithUTF8String:providerC];
			NSString * couponCode = (couponCodeC == NULL) ? @"" : [NSString stringWithUTF8String:couponCodeC];
			NSString * idCoupon = (idCouponC == NULL) ? @"" : [NSString stringWithUTF8String:idCouponC];
			NSString * position = (positionC == NULL) ? @"" : [NSString stringWithUTF8String:positionC];
			Coupon * coupon = [[Coupon alloc]initWithId:idCoupon 
											 name:name position:position provider:provider 
											 couponCode:couponCode descriptions:descriptions];
			[coupons addObject:coupon];			
			[coupon release];
		}
	}
	else
	{
		NSLog(@"ERREUR LORS DE LA RECUPERATION<");
	}
	
	sqlite3_finalize(smt);
	return coupons;
}
# pragma mark -



@end
